package com.ybear.ybnetworkutil.http;

import java.util.concurrent.TimeUnit;

import okhttp3.CookieJar;
import okhttp3.OkHttpClient;

/**
 * 网络请求
 */
public class HttpClient {
    private OkHttpClient.Builder mBuilder;
    private HttpReboot mHttpReboot;
    private HttpClient() { }
    private static final class HANDLER { private static final HttpClient I = new HttpClient(); }
    public static HttpClient create() {
        HttpClient req = HANDLER.I;
        req.mBuilder = new OkHttpClient().newBuilder();
        //默认连接超时
        req.connectTimeout( 45 );
        //默认回调超时
        req.callTimeout( 120 );
        //默认读取超时
        req.readTimeout( 120 );
        //默认写入超时
        req.writeTimeout( 120 );
        return req;
    }

    public Req build() { return Req.create().initClient( mBuilder.build(), mHttpReboot ); }

    /**
     * 设置重连机制
     * @param reboot    重连机制
     * @return          this
     */
    public HttpClient setHttpReboot(HttpReboot reboot) {
        mHttpReboot = reboot;
        return this;
    }

    /**
     * 设置连接超时时间
     * @param timeout   超时时间
     * @param unit      时间单位
     * @return          this
     */
    public HttpClient connectTimeout(long timeout, TimeUnit unit) {
        mBuilder.connectTimeout(timeout, unit);
        return this;
    }
    public HttpClient connectTimeout(long timeout) {
        return connectTimeout(timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置回调超时时间
     * @param timeout   超时时间
     * @param unit      时间单位
     * @return          this
     */
    public HttpClient callTimeout(long timeout, TimeUnit unit) {
        mBuilder.callTimeout(timeout, unit);
        return this;
    }
    public HttpClient callTimeout(long timeout) {
        return callTimeout(timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置读取超时时间
     * @param timeout   超时时间
     * @param unit      时间单位
     * @return          this
     */
    public HttpClient readTimeout(long timeout, TimeUnit unit) {
        mBuilder.readTimeout(timeout, unit);
        return this;
    }
    public HttpClient readTimeout(long timeout) {
        return readTimeout(timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置写入超时时间
     * @param timeout   超时时间
     * @param unit      时间单位
     * @return          this
     */
    public HttpClient writeTimeout(long timeout, TimeUnit unit) {
        mBuilder.writeTimeout(timeout, unit);
        return this;
    }
    public HttpClient writeTimeout(long timeout) {
        return writeTimeout(timeout, TimeUnit.SECONDS);
    }

    /**
     * cookie
     * @param cookieJar     回调
     * @return              this
     */
    public HttpClient cookieJar(CookieJar cookieJar) {
        mBuilder.cookieJar( cookieJar );
        return this;
    }
}
